<template>
  <!-- 登录之后的首页主体框架 -->
  <el-container class="bg-main">
    <el-header class="p-fixed w-percent100" style="padding:0 30px;top:0;z-index:2">
      <!--顶部头部组件 -->
      <transition name="el-fade-in-linear" >
        <v-navbar />
      </transition>
    </el-header>
    <el-container :style="{'height':slide_h+'px'}"  style="padding:60px 0 0 30px;">
      <transition name="el-fade-in-linear">
        <!-- 侧边菜单栏 -->
        <el-aside style="width:220px;overflow-y:auto;background-color: rgb(50, 64, 87);margin-top:10px;" >
          <v-slideMenu nav_model="vertical"/>
        </el-aside>
      </transition>
      <!-- 中间工作区域组件 -->
      <el-container>
        <el-main>
          <v-bread :breadcrumb_list="breadcrumb_list"/>
          <div style="height:10px"></div>
          <v-main id="pagemain"  />
          <div v-if="breadcrumb_list.length===1">
            <!-- 首页进入之后的数据 -->
            <homePage />
          </div>
        </el-main>
      </el-container>
    </el-container>
  </el-container>
</template>
<script>
  const main = () =>
    import ('@/components/Main')
  const slideMenu = () =>
    import ('@/components/menu/slideMenu')
  const navbar = () =>
    import ('@/components/header/Navbar')
  const bread = () => import ("@/components/Breadcrumb/breadtemplate")
  const dialog_impanel = () => import ("@/components/im/imPanel")
  const homePage = () => import ("@/components/home/homePage")
  export default {
    components: {
      'v-main': main,
      'v-slideMenu': slideMenu,
      'v-navbar': navbar,
      'v-bread': bread,
      'homePage':homePage,
      'dialog_impanel':dialog_impanel
    },
    computed: {
      breadcrumb_list () {
        //获取当前的路由堆栈,并生成面包屑路径
        return this.$route.matched
      }
    },
    data() {
      return {
        dialoginfo: {
          show:0,
          title:'',
          url:'',
          data:''
        },
        HEARTBEAT_TIME:this.$store.getters.getValForKey("HEARTBEAT_TIME"),
        clock:null,
        cmdLen:this.$store.getters.getValForKey("cmdLen"),
        CMD:this.$store.getters.getValForKey("CMD"),
        CMDHander:this.$store.getters.getValForKey("CMDHander"),
        CMDReverse:{},
        wsurl:location.protocol.indexOf("s")>=0?"wss:":"ws:"+"//"+this.proAPI.WS_DOMAIN+":9326/showcase",
        showchannels:true,
        slide_h:window.document.body.offsetHeight
      }
    },
    methods: {
      beforeshowimPanel(){
        if(this.$store.state.ws!=null&&this.$store.state.ws.readyState!=1){
          const loading = this.$loading({
            lock: true,
            text: '连接客服系统...',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          });
          this.initWs();
          loading.close();
        }else{
          this.showchannels=this.showchannels;
        }
      },
      showimPanel(x){
        this.$store.state.currentToId = {"channel":x.sid,"nickName":x.sname,"state":1};
        x.badge=0;
        this.dialoginfo = {
          show:1,
          title:"【"+x.sname+"】的会话",
          url:"",
          data:x
        };
      },
      changshowchannels(){
        alert(123);
        this.showchannels=!this.showchannels;
      },
      initWs(){
        this.initCMDReverse();
        console.log(this.$store.getters.getUserInfo);
        this.$store.commit("initws",this.wsurl+"?id=c"+this.$store.getters.getUserInfo.id);
        this.$store.state.ws.onopen = (event, ws) => {
          this.ping();
        };
        this.$store.state.ws.onmessage = (event, ws) => {
          var arrayBuffer = event.data;
          // console.log('receive data: ', arrayBuffer, ws)
          var uint8array = null;
          var firstbyte = new Uint8Array(arrayBuffer, 0, 2);
          var firstchar = new TextDecoder('utf-8').decode(firstbyte);
          var isZipped = false;
          var isZippedStr = '';
          if (firstchar.indexOf('x') != -1) {
            // 压缩过的
            isZipped = true;
            isZippedStr = '(zipped)';
            var zipedUint8array = new Uint8Array(arrayBuffer, 2);
            uint8array = pako.ungzip(zipedUint8array);
          } else {
            uint8array = new Uint8Array(arrayBuffer);
          }
          var data = new TextDecoder('utf-8').decode(uint8array);
          console.log('receive data' + isZippedStr + ': ' + data)
          if (!data || data.length < this.cmdLen) {
            console.error('data wrong' + isZippedStr + ', the data length must be >= ' + this.cmdLen, data);
            return;
          }
          var commandstr = data.substr(0, this.cmdLen);
          console.log(commandstr);
          var commandName = this.CMDReverse[commandstr];
          if (!commandName) {
            console.error('commandstr is ' + commandstr + isZippedStr + ', but con not find commandName');
            return;
          }
          if (!this.CMDHander[commandName]) {
            console.error('can not found siteImBsHandler, commandName is ' + commandName + isZippedStr);
            return;
          }
          if (data.length > this.cmdLen) {
            var bodyStr = data.substr(this.cmdLen);

            console.log('received:' + commandName + isZippedStr + '\r\n, body string is :' + bodyStr);
            var bodyObj = null;
            try {
              bodyObj = JSON.parse(bodyStr);
              console.log(bodyObj);
            } catch (error) {
              console.error(
                'can not parse to object, commandName is ' +
                commandName +
                isZippedStr +
                ', body string is ' +
                bodyStr
              );
              return;
            }
            // console.log("received " + commandName + ", body string is :" + bodyStr);
            this.CMDHander[commandName](this.$store.state.ws, event, commandName, bodyStr, bodyObj,this.$store);
          } else {
            console.log('received:' + commandName + isZippedStr + ', body string is null');
            this.CMDHander[commandName](this.$store.state.ws, event, commandName, null, null,this.$store);
          }
        };
        this.$store.state.ws.onclose = (event, ws) => {
          this.clock!=null?clearTimeout(this.clock):"";
        };
        this.$store.state.ws.onerror = (event, ws)=> {
          this.clock!=null?clearTimeout(this.clock):"";
        };
      },
      initCMDReverse(){
        for (var cmdName in this.CMD) {
          var commandValue = this.CMD[cmdName];
          this.CMDReverse[this.formatCommand(commandValue)] = cmdName;
        }
        console.log(this.CMDReverse);
      },
      sendInfo(command, bodyObj) {
        if(!this.$store.state.ws||this.$store.state.ws.readyState!=1){
          console.error("ws状态不正确");
          clearTimeout(this.clock);
          return;
        }
        var commandname = this.CMDReverse[command]; //HEARTBEAT_REQ
        var str = command;
        if (bodyObj) {
          str = command + JSON.stringify(bodyObj);
        }
        console.log('准备发送 ' + commandname + ":'" + str + "'");
        var uint8array = new TextEncoder().encode(str);
        this.$store.state.ws.send(uint8array.buffer);
      },
      ping(data){
        this.sendInfo(this.CMD.HEARTBEAT_REQ,null);
        this.clock = setTimeout(()=>{
          this.ping();
        },this.HEARTBEAT_TIME)
      },
      formatCommand(command){
        var commandstr = command + "";
        if (commandstr.length < this.cmdLen) {
          var gap = this.cmdLen - commandstr.length;
          var supplystr = "";
          for (var index = 0; index < gap; index++) {
            supplystr += "0";
          }
          if (command < 0) {
            commandstr = "-" + supplystr + commandstr.substring(1);
          } else {
            commandstr = supplystr + commandstr;
          }
        }
        // log("init command: " + command + ", fomatted command: " + commandstr);
        return commandstr;
      },
      changedialogshow() {
        this.dialoginfo= {
          show:0,
          title:'',
          url:'',
          data:''
        }
      },
    },

    beforeCreate: function() {
    },
    created: function() {
    },
    beforeMount: function() {
      // console.log("beforeMount");
    },
    mounted: function() {
      var initIM = setInterval(()=>{
        if(this.$store.getters.getUserInfo!=null){
          this.initWs();
          clearInterval(initIM);
        }else{
          console.log("还没获取到");
        }
      },3000)
    },
    beforeUpdate: function() {
      // console.log("beforeUpdate");
    },
    updated: function() {
      // console.log("updated");
    },
    activated: function() {
      // console.log("activated");
    },
    deactivated: function() {
      // console.log("deactivated");
    },
    beforeDestroy: function() {
      // console.log("beforeDestroy");
    },
    destroyed: function() {
      // console.log("destroyed");
    },
    errorCaptured: function(err, vm, info) {
      // console.log(err);
      // console.log(vm);
      // console.log(info);
    }
  }
</script>
<style scoped lang="scss">
  .bg-main{
    height:100%;
    /*background-color:#f6f7fb*/
  }
  .el-header,
  .el-footer {
    /*background-color: #38cb7d;*/
    background-color: rgb(0, 63, 119);
    color: #ffffff;
    text-align: center;
    line-height: 60px;
    padding-left: 0
  }
  .el-main{
    padding:10px 8px
  }
</style>
